# ---------------------------------------------------------------------------
# Author: jachymko
# Desc:   Functions to manipulate images.
# Date:   Dec 13, 2006
# Site:   http://www.codeplex.com/PowerShellCX
# Usage:  In your profile place the following command:
#  
#         . "$Env:PscxHome\Profile\Imaging.ps1"
# ---------------------------------------------------------------------------

[void][Reflection.Assembly]::LoadWithPartialName('System.Drawing')

function Export-Jpeg {
    param (
        $fileName = $(throw 'No filename specified'), 
        $quality = 75   
    )
    
    begin {
        function Get-ImageEncoder($mimeType) {
            [Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() |? {
                $_.MimeType -eq $mimeType
            }
        }
        
        $encoder = Get-ImageEncoder image/jpeg 
        $qualityParam = new-object Drawing.Imaging.EncoderParameter `
                                 ([Drawing.Imaging.Encoder]::Quality, [long]$quality)
        
        $encoderParams = new-object Drawing.Imaging.EncoderParameters 1
        $encoderParams.Param[0] = $qualityParam 
    }
    
    process {
        $thisName = $fileName
    
        if($thisName -is [ScriptBlock]) {
            $thisName = $($_ | & $thisName)
        }
    
        if($thisName -notmatch '\.jp(e?)g$') {
            $thisName += '.jpeg'
        }
        
        $folder = (split-path $thisName)
        $thisName = (split-path $thisName -leaf) 
        if(-not ($folder)) { 
            $folder = '.' 
        }
        
        $thisName = join-path (resolve-path $folder) $thisName
        $_.Save($thisName, $encoder, $encoderParams)
    }
}

function Resize-Bitmap($width, $height) {
    begin {
        $unsupportedPixelFormats = 'Format1bppIndexed', 'Format4bppIndexed', 
            'Format8bppIndexed', 'Format16bppArgb1555', 'Format16bppGrayScale',
            'Undefined', 'DontCare'
    }
    process {
        if($unsupportedPixelFormats -contains $_.PixelFormat) {
            write-error "Pixel format $($_.PixelFormat) is not supported."
        }
        else {
            $bmp = new-object Drawing.Bitmap $width, $height, $_.PixelFormat
            $gfx = [Drawing.Graphics]::FromImage($bmp)
            
            $gfx.SmoothingMode = 'HighQuality'
            $gfx.InterpolationMode = 'HighQualityBicubic'
                        
            $gfx.DrawImage($_, 0, 0, $width, $height)
            $gfx.Dispose()
            
            $bmp    
        }
    }   
}
